<template>
  <!-- 右侧部分 -->
  <div class="card" style="margin-bottom: 10px">
    <!-- 头部 -->
    <div style="display: flex; align-items: flex-start">
      <p style="margin: 0; color: black; font-weight: bold; font-size: 20px">
        作业批改
      </p>
      <p
        style="
          margin: 0;
          color: grey;
          font-size: 14px;
          margin-left: 10px;
          margin-top: 4px;
        "
      >
        请设置课程的相关简介
      </p>
    </div>
  </div>
  <!-- 查询和选择框 -->
  <!-- 查询栏 -->
  <div class="card" style="margin-bottom: 10px">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <!-- 选择框 -->
      <el-select
        v-model="selected_id"
        clearable
        placeholder="选择章节"
        style="text-align: center; width: 260px"
        popper-class="select-popper"
        @change="handleChapterChange"
      >
        <el-option
          v-for="item in options"
          :key="item.homework_id"
          :label="item.title"
          :value="item.homework_id"
        ></el-option>
      </el-select>

      <!-- 查询 -->
      <div style="display: flex; align-items: center">
        <el-input
          style="width: 100%; margin-right: 10px"
          placeholder="输入学生姓名进行查找"
          prefix-icon="el-icon-search"
          v-model="searchName"
        ></el-input>
        <el-button type="primary" round @click="handleSearch" disabled>查询</el-button>
      </div>
    </div>
  </div>

  <!-- 表格 -->
  <div class="card" style="margin-bottom: 10px">
    <div>
      <!-- 表格内容 -->
      <!-- 在您的 <el-table> 组件中，prop 属性用于定义每一列应该显示数据对象中的哪个属性。 -->
      <el-table :data="paginatedItems" :fit="true" style="width: 100%">
        <el-table-column
          prop="stu_number"
          label="学生学号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="title"
          label="作业章节名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="content"
          label="提交内容"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="attachment_url"
          label="上传的文件/作业"
          align="center"
        >
          <template #default="{ row }">
            <!-- <el-link
              type="primary"
              :underline="false"
              @click="handleViewFile(row.attachment_url)"
            >
              下载作业
            </el-link> -->
            <div v-if="row.attachment_url!=null">
            <a
            type="primary"
            :underline="false"
            :href="row.attachment_url"
            download
            >
            查看作业
          </a>
            </div>
            <div v-else>无附件</div>
          </template>
        </el-table-column>
        <el-table-column label="得分" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.getscore"
              @change="handleScoreChange(row)"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!-- 分页符 使用flex布局 未实现逻辑！！！-->
  <div class="card" style="display: flex; justify-content: flex-end">
    <el-pagination
      background
      layout="prev, pager, next"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      @current-change="handlePageChange"
    ></el-pagination>
  </div>
</template>
  
  
  
  <script setup>
import { ref, onMounted,computed } from "vue";
import { ElMessage } from "element-plus";
import api from "@/api/axios.js"


const currentPage = ref(1); // 当前页码
const pageSize = ref(10);   // 每页显示的条目数
const total = ref();     // 总条目数（通常从服务器获取）
// 定义需要使用的数据
const semId=1;//具体从rounter里拿
const selected_id=ref("");
const options = ref([]);
// 表格数据
const tableData = ref([{
  username:'czy',
},]);
//页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
};
const filteredData = computed(() => {
  // 过滤数据
  return tableData.value.filter(item => {
    return Object.values(item).some(value =>
      String(value).toLowerCase().includes(searchName.value.toLowerCase())
    );
  });
});
const paginatedItems = computed(() => {
  // const nameTable=tableData.value.filter((item)=>{
  //   item.username.includes(searchName.value)
  // })
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});
//钩子：获取本课程单元
onMounted(async () => {
      try {
        const response = await api.FetchHmkListBySem(semId);
        console.log(JSON.stringify(response,null,2))
        if(response.data.status==1){
          options.value = response.data.data;
          // selected_id.value=options.value[0].homework_id
        }

      else {
        ElMessage({
        type: "error",
        message: "单元获取失败！",
      });
      }
      } catch (error) {
        console.error('Error fetching options:', error);
      }
    });
//获取相应unit_id的学生作业
const UnitStuHmk=async(id)=>{
  try{
    const response = await api.FetchListByhmkid(id);
        console.log(JSON.stringify(response,null,2))
        if(response.data.status==1){
          tableData.value= response.data.data;
          total.value=tableData.value.length
        }
      else {
        ElMessage({
        type: "error",
        message: "批改列表获取失败！",
      });
  }
  }catch(err){
    console.error('Error fetching options:', err);
  }
}

// 多选框筛选逻辑 使用计算属性
const handleChapterChange = async(newValue) => {
  selected_id.value = newValue;
  await UnitStuHmk(selected_id.value);
};

//查询按钮逻辑
const searchName = ref("");
// 当点击查询按钮时触发过滤操作

const originalTableData = ref([]);
const handleSearch = () => {
  if (searchName.value) {
    // 从原始数据中过滤
    tableData.value = tableData.value.filter((item) =>
      item.username.includes(searchName.value)
    );
  } else {
    // 如果没有搜索内容，则重置为原始数据
    tableData.value = [...originalTableData.value];
  }
};

// 处理得分变化
const handleScoreChange = async(row) => {
  // 在这里可以添加一些验证逻辑，确保得分符合要求
  // 这里暂时没有添加验证逻辑，您可以根据需要进行补充
  if (row.getscore > 100) {
    ElMessage({
      type: 'error',
      message: '得分不能高于 100！',
    });
    return; // 如果得分超过 100，则不更新表格数据
  }
  if (row.getscore < 0) {
    ElMessage({
      type: 'error',
      message: '得分不能低于 100！',
    });
    return; // 如果得分超过 100，则不更新表格数据
  }

  // 更新表格数据中对应学生的得分
  const student = tableData.value.find((item) => item.stu_number === row.stu_number);
  if (student) {
    await UpdateHmkGrade(student);
    student.Score = row.getscore;
  }
};
//后端修改学生作业分数
const UpdateHmkGrade=(async(data)=>{
  try{
    const response = await api.UpdateGrade(data);
        if(response.data.status==1){
          ElMessage({
        type: "success",
        message: "批改成功！",
      })
        }
      else {
        ElMessage({
        type: "error",
        message: "批改失败！",
      });
  }
  }catch(err){
    console.error('Error fetching options:', err);
  }
})
</script>
  
  <style scoped>
.card {
  background-color: #fff;
  border-radius: 5px;
  padding: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>